<template>
  <div class="content-box">
    <div class="page-title">
      添加活动
    </div>
    <div class="form-box">
      <el-form style="padding: 20px;" :model="form" label-width="80px" :rules="postRules" ref="postRef">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="参与人数" prop="participantsNumber">
          <el-input v-model="form.participantsNumber" placeholder="请输入参与人数" />
        </el-form-item>
        <el-form-item label="支出情况" prop="expenditure">
          <el-select style="width: 100%;" v-model="form.expenditure" placeholder="请选择">
            <el-option v-for="dict in youOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
          <!--          <el-input v-model="form.expenditure" placeholder="请输入支出情况" />-->
        </el-form-item>
        <el-form-item label="收费情况" prop="charge">
          <!--          <el-input v-model="form.charge" placeholder="请输入收费情况" />-->
          <el-select style="width: 100%;" v-model="form.charge" placeholder="请选择">
            <el-option v-for="dict in youOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select style="width:100%;" v-model="form.activityType" placeholder="请选择活动类型">
            <el-option v-for="item in activityTypeOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动方式" prop="activityFormat">
          <el-select style="width:100%;" v-model="form.activityFormat" placeholder="请选择活动进行方式">
            <el-option v-for="item in activityOngoingOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
            placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="form.endTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
            placeholder="请选择结束时间" />
        </el-form-item>
        <el-form-item label="活动地点" prop="place">
          <el-input v-model="form.place" placeholder="请选择活动地点" />
        </el-form-item>
        <el-form-item label="活动介绍" prop="activityIntroduction">
          <el-input type="textarea" v-model="form.activityIntroduction" placeholder="请选择活动介绍" />
        </el-form-item>

        <el-form-item label="活动图片">
          <el-upload v-model="upimageFiles" name="file" list-type="picture-card" :action="uploadUrl"
            :on-success="handleImageSuccess" :limit="1" :before-upload="handleImageBeforeUpload"
            :on-exceed="handleImageExceed" :headers="headers" :before-remove="handleImageBeforeRemove"
            :file-list="upimageFileList">
            <Plus style="width: 25px;color: darkgray;"></Plus>
            <!--          <el-button size="default" type="primary">上传活动照片</el-button>-->
          </el-upload>
        </el-form-item>

        <el-form-item label="活动视频">
          <el-upload style="margin-top: 20px;" v-model="upfiles" name="file" :action="uploadUrl"
            :on-success="handleSuccess" :limit="1" :before-upload="handleBeforeUpload" :on-exceed="handleExceed"
            :headers="headers" :before-remove="handleBeforeRemove" :file-list="upfileList">
            <el-button size="default" type="primary">上传活动视频</el-button>
          </el-upload>
        </el-form-item>

        <div style="display: flex;margin-top: 40px;padding-bottom: 40px;">
          <el-button style=" width: 50%;" @click="onCancel">返回</el-button>
          <el-button style="width: 50%;" type="primary" @click="onSubmit">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getDictByCode } from '@/views/yearCheck/ykb/mf/mf'
import { wrapperLoadViteEnv } from '~/build/utils'
import db from '@/storage'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addHuoDong, createQrCodeUrl } from '@/views/yearCheck/ykb/otherApi'
import { useUserStore } from '@/store'

const upfiles = ref([])
const upfileList = ref([])
const upimageFiles = ref([])
const upimageFileList = ref([])
const headers = ref([])
const uploadUrl = ref('')
const activityOngoingOptions = ref([])
const activityTypeOptions = ref([])
const postRef = ref()

const youOptions = ([{ id: 1, name: '有' }, { id: 2, name: '无' }]);
const postRules = ({
  activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  participantsNumber: [{ required: true, message: '请输入参与人数', trigger: 'blur' }],
  expenditure: [{ required: true, message: '请选择', trigger: 'change' }],
  charge: [{ required: true, message: '请选择', trigger: 'change' }],
  activityType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  // activityFormat: [{ required: true, message: '请选择活动方式', trigger: 'change' }],
  // startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  // endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  place: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  activityIntroduction: [{ required: true, message: '请输入活动介绍', trigger: 'blur' }]
})
// do not use same name with ref
const form = reactive({
  activityFormat: '',//活动进行方式
  activityIntroduction: '',//活动介绍
  activityName: '',//活动名称
  activityType: '',//($int32)活动类型
  approvalResult: '',//($int32)审批结果(0：未审批；1：审批通过；2审批未通过)
  charge: '',//收费情况
  createBy: '',//
  createTime: '',//($date-time)
  endTime: '',//($date-time)结束时间 yyyy-MM-dd
  expenditure: '',//支出情况
  id: '',//
  imgFileUrl: '',//附件路径
  isDeleted: '',//($int32)是否删除：0-否、1-是
  likes: '',//点赞数
  mpFileUrl: '',//附件路径
  participantsNumber: '',//($int32)参与人数
  place: '',//地点
  remark: '',//
  socialCode: '',//社会组织编码
  startTime: '',//($date-time)开始时间 yyyy-MM-dd,
  imgFileName: '',
  mpFileName: ''
})

const onSubmit = () => {
  console.log(upimageFileList.value)
  console.log(upfileList.value)
  postRef.value.validate().then(() => {
    if (upimageFiles.value.length == 0) {
      ElMessage({
        message: ' 请上传活动图片',
        type: 'warning',
        plain: true,
      })
      return;
    }
    if (upfiles.value.length == 0) {
      ElMessage({
        message: ' 请上传活动视频',
        type: 'warning',
        plain: true,
      })
      return;
    }
    form.imgFileUrl = upimageFileList.value[0].response.data
    form.mpFileUrl = upfileList.value[0].response.data
    form.imgFileName = upimageFileList.value[0].name
    form.mpFileName = upfileList.value[0].name
    form.socialCode = localStorage.getItem('creditCode')
    console.log(form)
    addHuoDong(form).then(response => {
      console.log(response.data)
      if (response.code == 200) {
        ElMessage({
          message: '活动添加成功',
          type: 'success',
          plain: true,
        })
        history.back();
      }
    })
  })
}

const handleImageSuccess = (response, file, imageFileList) => {
  console.log("handleImageSuccess")
  upimageFileList.value = imageFileList   // 更新已上传的图片列表
  if (upimageFiles.value == null) {
    upimageFiles.value = []
  }
  upimageFiles.value.push(response.data)
  console.log(upimageFiles.value)
}
const handleImageBeforeRemove = (file, imageFileList) => {
  console.log("handleImageBeforeRemove")
  const index = upimageFileList.value.indexOf(file) // 获取当前被移除的图片索引
  if (index !== -1) {
    upimageFileList.value.splice(index, 1) // 从数据源中移除该图片
    upimageFiles.value.splice(index, 1)
  }
}
const handleImageExceed = (imageFiles, imageFileList) => {
  console.log("handleImageExceed")
  ElMessage({
    message: '只能上传一张图片',
    type: 'warning',
    plain: true,
  })
}
const handleImageBeforeUpload = (file) => {
  console.log("handleImageBeforeUpload")
  headers.value = { Authorization: 'Bearer ' + db.get('token') }
  console.log(file)
  if (file.size < 20) {
    ElMessage({
      message: '不能上传空文件',
      type: 'warning',
      plain: true,
    })
    return false // 返回false停止上传
  }
  return true
}
const handleSuccess = (response, file, fileList) => {
  upfileList.value = fileList   // 更新已上传的图片列表
  if (upfiles.value == null) {
    upfiles.value = []
  }
  upfiles.value.push(response.data)
  console.log(upfiles.value)
},
  handleBeforeRemove = (file, fileList) => {
    const index = upfileList.value.indexOf(file) // 获取当前被移除的图片索引
    if (index !== -1) {
      upfileList.value.splice(index, 1) // 从数据源中移除该图片
      upfiles.value.splice(index, 1)
    }
  }
const handleExceed = (files, fileList) => {
  ElMessage({
    message: '只能上传一个视频',
    type: 'warning',
    plain: true,
  })
}
const handleBeforeUpload = (file) => {
  headers.value = { Authorization: 'Bearer ' + db.get('token') }
  console.log(file)
  if (file.size < 20) {
    ElMessage({
      message: '不能上传空文件',
      type: 'warning',
      plain: true,
    })
    return false // 返回false停止上传
  }
  return true
}

const onCancel = () => {
  history.back()
}
onMounted(() => {
  const userStore = useUserStore();
  localStorage.setItem("creditCode", userStore.userInfo.workNo)
  const viteEnv = wrapperLoadViteEnv(import.meta.env)
  uploadUrl.value = viteEnv.VITE_BASE_URL_API + 'hbsys-system/minio/upload'
  getDictByCode('activityOngoing').then(response => {
    activityOngoingOptions.value = response.data
  })
  getDictByCode('activityType').then(response => {
    activityTypeOptions.value = response.data
  })

})
</script>


<style lang="scss" scoped>
::v-deep .el-form-item__label {
  justify-content: flex-start !important;
}

::v-deep .el-upload--picture-card {
  width: 80px;
  height: 80px
}

.content-box {
  padding: 0 10px;
  padding-top: 10px;
  // height: 90vh;
  background-color: #f5f6f8;

  .form-box {
    background-color: #fff;
    padding: 10px;
  }
}

.page-title {
  height: 40px;
  text-align: center;
  font-size: 20px;
}
</style>
